package com.linkage.educloud.ah.view.activity.classspace;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.linkage.educloud.ah.Constants;
import com.linkage.educloud.ah.R;
import com.linkage.educloud.ah.adapter.pic.ChooseImgAdapter;
import com.linkage.educloud.ah.bean.AccountData;
import com.linkage.educloud.ah.config.AccountConfig;
import com.linkage.educloud.ah.evenbus.DynamicEvent;
import com.linkage.educloud.ah.mvp.contract.dynamic.IDynamicWriteContract;
import com.linkage.educloud.ah.mvp.presenter.dynamic.DynamicWritePresenter;
import com.linkage.educloud.ah.view.BasicTitleActivity;
import com.linkage.educloud.ah.widget.NoScrollGridView;
import com.linkage.educloud.ah.widget.PanelView;
import com.zzhou.common.library.util.ToastShow;
import com.zzhou.common.library.util.Utils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Mr'Tang on 2018/10/9.
 */

public class DynamicWriterTextActivity extends BasicTitleActivity implements IDynamicWriteContract.IView, View.OnTouchListener {

    static String KEY_TYPE = "type";
    static String KEY_ID = "class_id";

    //使用BindView后 如果需要传递这个view会报空指针,所以这里我采用传统的findviewbyid
    EditText ac_write_text_ed;

    @BindView(R.id.ac_write_text_face)
    ImageView ac_write_text_face;
    @BindView(R.id.ac_write_text_quick)
    TextView ac_write_text_quick;
    @BindView(R.id.ac_write_text_notice)
    LinearLayout ac_write_text_notice;
    @BindView(R.id.ac_write_text_notice_box)
    CheckBox ac_write_text_notice_box;
    @BindView(R.id.ac_write_text_album)
    LinearLayout ac_write_text_album;
    @BindView(R.id.ac_write_text_album_box)
    CheckBox ac_write_text_album_box;
    @BindView(R.id.ac_write_text_panel)
    PanelView ac_write_text_panel;
    @BindView(R.id.ac_write_text_imggrid)
    NoScrollGridView ac_write_text_imggrid;

    int is_visibility = 1;//表情是否展示中

    List<Uri> img_list = new ArrayList<>();
    ChooseImgAdapter adapter;
    AccountData accountData;
    String picUrls = "";
    int type = 0;//0--发文字 1--发图片

    IDynamicWriteContract.IPresenter iPresenter;

    /**
     * @param context
     * @param type    0--发文字 其他--发图片
     */
    public static void launch(Context context, int type, String class_id) {
        Intent intent = new Intent(context, DynamicWriterTextActivity.class);
        intent.putExtra(KEY_TYPE, type);
        intent.putExtra(KEY_ID, class_id);
        context.startActivity(intent);
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_dynamic_write_text;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        accountData = AccountConfig.getLoginAccount();
        iPresenter = new DynamicWritePresenter(this, this);
        ac_write_text_ed = findViewById(R.id.ac_write_text_ed);
        ac_write_text_ed.setOnTouchListener(this);
        initFace();
        type = getIntent().getIntExtra(KEY_TYPE, 0);
        if (type == 0) {
            ac_write_text_imggrid.setVisibility(View.GONE);
            ac_write_text_album.setVisibility(View.GONE);
            setTitle("发文字");
        } else {
            ac_write_text_imggrid.setVisibility(View.VISIBLE);
            ac_write_text_album.setVisibility(View.VISIBLE);
            adapter = new ChooseImgAdapter(DynamicWriterTextActivity.this, img_list);
            ac_write_text_imggrid.setAdapter(adapter);
            setTitle("发图片");
        }
        //教师显示发不到公告
        if (accountData.getUserType() == 1) {
            ac_write_text_notice.setVisibility(View.VISIBLE);
        } else {
            ac_write_text_notice.setVisibility(View.GONE);
        }

        ac_write_text_quick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Editable editable = ac_write_text_ed.getText();
                editable.insert(ac_write_text_ed.getSelectionStart(), ac_write_text_quick.getText().toString().trim());
            }
        });

        showZloading();
        iPresenter.getTheme(getIntent().getStringExtra(KEY_ID), Utils.getVersion(this));
    }

    //获取主题回调
    public void changeTheme(String msg) {
        hideZloading();
        ac_write_text_quick.setText(msg);
    }

    //发送点击事件
    private void send() {
        int photo_sync;
        if (type == 0) {
            if (ac_write_text_ed.getText().toString().trim().isEmpty()) {
                ToastShow.show(this, "内容不能为空");
                return;
            }
            photo_sync = -1;
        } else {
            if (img_list.size() == 0 || img_list == null) {
                ToastShow.show(this, "请选择图片");
                return;
            }
            if (ac_write_text_ed.getText().toString().trim().isEmpty()) {
                ToastShow.show(this, "内容不能为空");
                return;
            }
            if (ac_write_text_album_box.isChecked()) {
                photo_sync = 0;
            } else {
                photo_sync = -1;
            }
        }
        int notice_sync;
        if (accountData.getUserType() == 1) {
            if (ac_write_text_notice_box.isChecked()) {
                notice_sync = 0;
            } else {
                notice_sync = -1;
            }
        } else {
            notice_sync = -1;
        }
        showZloading();
        if (type == 0) {
            iPresenter.senddynamicmsg(getIntent().getStringExtra(KEY_ID), accountData.getUserId(), getIntent().getIntExtra(KEY_TYPE, 0) == 0 ? 1 : 2, accountData.getUserType(), ac_write_text_ed.getText().toString().trim(), picUrls, photo_sync, notice_sync);
        } else {
//            List<File> list = new ArrayList<>();
//            for (Uri uri : img_list) {
//                list.add(new File(uri.getPath()));
//            }
            iPresenter.senddynamicattachment(1, getIntent().getStringExtra(KEY_ID), new File(img_list.get(0).getPath()));
        }
    }

    //发送完成 关闭界面刷新列表
    public void addSuccess() {
        hideZloading();
        EventBus.getDefault().post(new DynamicEvent(DynamicEvent.add_dynamic, 0, null));
        finish();
    }

    //图片发送完的回调
    public void afterSendPic(String url) {
        picUrls = picUrls.isEmpty() ? url : picUrls + "," + url;
        type = 0;
        send();
    }

    //初始化表情相关
    private void initFace() {
        ac_write_text_panel.installView(2, 2, ac_write_text_ed);
        ac_write_text_face.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (is_visibility == 1) {
                    ac_write_text_face.setImageResource(R.mipmap.ic_btn_face_on);
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(DynamicWriterTextActivity.this.getCurrentFocus().getWindowToken(), 0);
                    //延时0.3秒 以解决表情栏展示比隐藏输入法快,界面被顶上去的bug（目前没想到其他好方法）
                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ac_write_text_panel.setVisibility(View.VISIBLE);
                        }
                    }, 300);
                    is_visibility = 0;
                } else if (is_visibility == 0) {
                    ac_write_text_face.setImageResource(R.mipmap.ic_btn_face_off);
                    ac_write_text_panel.setVisibility(View.GONE);
                    is_visibility = 1;
                }
            }
        });
    }

    //暴露给表情组件调用 用于点了输入框改变表情状态
    public void change() {
        ac_write_text_face.setImageResource(R.mipmap.ic_btn_face_off);
        ac_write_text_panel.setVisibility(View.GONE);
        is_visibility = 1;
    }

    //选择照片回调相关
    @Override
    public void onActivityResult(int requestCode, int resultCode,
                                 final Intent data) {
        switch (requestCode) {
            case Constants.PIC.PIC_ALBUM://相册选择回调
                if (data != null) {
                    Uri uri = data.getData();
                    img_list.add(uri);
                    adapter.notifyDataSetChanged();
                }
                break;
            case Constants.PIC.PIC_Shot://拍摄界面回调
                if (resultCode == RESULT_CANCELED) {
                    return;
                }
                File temp = new File(Environment.getExternalStorageDirectory()
                        + "/xiaoma.jpg");
                Uri uri = Uri.fromFile(temp);
                img_list.add(uri);
                adapter.notifyDataSetChanged();

                break;
        }
    }

    //重写onTouch方法
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        //触摸的是EditText控件，且当前EditText可以滚动，则将事件交给EditText处理；否则将事件交由其父类处理
        if ((view.getId() == R.id.ac_write_text_ed && canVerticalScroll(ac_write_text_ed))) {
            view.getParent().requestDisallowInterceptTouchEvent(true);
            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                view.getParent().requestDisallowInterceptTouchEvent(false);
            }
        }
        return false;
    }

    /**
     * EditText竖直方向是否可以滚动
     *
     * @param editText 需要判断的EditText
     * @return true：可以滚动   false：不可以滚动
     */
    private boolean canVerticalScroll(EditText editText) {
        if (editText.canScrollVertically(-1) || editText.canScrollVertically(1)) {
            return true;
        }
        return false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_send, menu);
        return super.onCreateOptionsMenu(menu);
    }

    public boolean onOptionsItemSelectedCompat(MenuItem item) {
        int i = item.getItemId();
        switch (i) {
            case R.id.menu_dynamic_send:
                send();
                break;
        }
        return false;
    }
}